package based

import (
	"fmt"
	"github.com/xuperchain/xuper-sdk-go/v2/account"
	"github.com/xuperchain/xuper-sdk-go/v2/xuper"
	"io/ioutil"
	"time"
)

func TestNativeContract(encrMap map[string]string) {
	codePath := "./contract/reinurance" // 编译好的二进制文件
	code, err := ioutil.ReadFile(codePath)
	if err != nil {
		panic(err)
	}

	acc, err := account.GetAccountFromPlainFile("./data/keys")
	//acc, err := account.CreateAndSaveAccountToFile("./keys", "private.key", 1, 1)
	//account, err := account.RetrieveAccount("玉 脸 驱 协 介 跨 尔 籍 杆 伏 愈 即", 1)
	if err != nil {
		fmt.Printf("retrieveAccount err: %v\n", err)
		return
	}
	fmt.Printf("retrieveAccount address: %v\n", acc.Address)
	contractAccount := "XC1111111111111111@xuper"
	strtime := string(time.Now().Unix())
	contractname := "Rein"
	contractName := contractname + strtime
	fmt.Println("合约名称：" + contractName)
	fmt.Printf("0")
	err = acc.SetContractAccount(contractAccount)
	if err != nil {
		panic(err)
	}

	fmt.Printf("1")
	xchainClient, err := xuper.New("127.0.0.1:37101")
	if err != nil {
		panic(err)
	}

	args := map[string]string{
		"creator": "test",
		"key":     "test",
	}
	fmt.Printf("2")
	tx, err := xchainClient.DeployNativeGoContract(acc, contractName, code, args)
	fmt.Printf("3")
	if err != nil {
		panic(err)
	}
	fmt.Printf("Deploy Native Go Contract Success! %x\n", tx.Tx.Txid)

	//调用合约：chaincode
	//var encrMap = server.GetContCR1()
	tx, err = xchainClient.InvokeNativeContract(acc, contractName, "EncryptCR", encrMap)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Invoke Native Go Contract Success! %x\n", tx.Tx.Txid)

	tx, err = xchainClient.QueryNativeContract(acc, contractName, "get", args)
	if err != nil {
		panic(err)
	}
	if tx != nil {
		fmt.Printf("查询结果：%s\n", tx.ContractResponse.Body)
	}
}
